package com.sc.common.util;


import com.alibaba.druid.pool.DruidDataSource;
import com.sc.common.entity.admin.datasource.SysDataSource;
import com.sc.common.enums.ApplicationEnum;
import org.apache.commons.codec.binary.Base64;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySources;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.UUID;

/**
 * @author ：wust
 * @date ：Created in 2019/9/3 15:47
 * @description：
 * @version:
 */
public class CommonUtil {

    private CommonUtil(){}


    // 判断字符串是十六进制显示
    public static boolean isHexStr(String str) {
        if (str == null || str.isEmpty())
            return false;
        int strLen = str.length();
        char c;
        for (int i = 0; i < strLen; i++) {
            c = str.charAt(i);
            if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
                return false;
        }
        return true;
    }

    // 整形转16进制字符串
    public static String intToHexStr(int source, int len) {
        String hexStr = String.format("%" + (len > 0 ? len : "") + "s",
                Integer.toHexString(source)).replace(' ', '0');
        return (len == 0) ? hexStr :
                hexStr.substring(hexStr.length() - len, hexStr.length());
    }

    // 16进制字符串转整形
    public static int hexStrToInt(String hexStr) {
        try {
            return Integer.valueOf(hexStr, 16);
        } catch (Exception e) {
            return 0;
        }
    }


    /**
     * 字符串转换为Ascii
     * @param value
     * @return
     */
    public static String stringToAscii(String value) {
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length - 1; i++) {
            sbu.append(intToHexStr((int) chars[i],2));
        }
        return sbu.toString();
    }


    public static String hexString2binaryString(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0) {
            return null;
        }
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++) {
            tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }


    public static String[] generateWebToken(String loginName) {
        String redisKey = String.format(ApplicationEnum.WEB_LOGIN_KEY.getStringValue(),loginName, UUID.randomUUID().toString());
        String tokenBase64 = Base64.encodeBase64String(redisKey.getBytes());
        String[] result = {redisKey,tokenBase64};
        return result;
    }


    public static String[] generateAppToken(String loginName) {
        String redisKey = String.format(ApplicationEnum.APP_LOGIN_KEY.getStringValue(),loginName,UUID.randomUUID().toString());
        String tokenBase64 = Base64.encodeBase64String(redisKey.getBytes());
        String[] result = {redisKey,tokenBase64};
        return result;
    }

    /**
     * 是否为系统超级管理员
     * @param accountType
     * @return
     */
    public static boolean isSuperAdminAccount(String accountType){
        if("A101701".equals(accountType)) {
            return true;
        }
        return false;
    }

    /**
     * 是否为系统普通管理员
     * @param accountType
     * @return
     */
    public static boolean isAdminAccount(String accountType){
        if("A101702".equals(accountType)) {
            return true;
        }
        return false;
    }

    /**
     * 是否为员工
     * @param accountType
     * @return
     */
    public static boolean isStaffAccount(String accountType){
        if("A101703".equals(accountType)) { // 员工账号
            return true;
        }
        return false;
    }

    /**
     * 是否为客户
     * @param accountType
     * @return
     */
    public static boolean isCustomer(String accountType){
        if("A101705".equals(accountType)) {
            return true;
        }
        return false;
    }


    /**
     * 获取userType，主要用于获取菜单、组织参数
     * @param accountType
     * @param defaultUserType
     * @return
     */
    public static String getPermissionType(String accountType,String defaultUserType){
        String permissionType = defaultUserType;
        if(CommonUtil.isSuperAdminAccount(accountType) || CommonUtil.isAdminAccount(accountType)){ // 平台挂你乐意
            permissionType = "A100401";
        }else if(CommonUtil.isStaffAccount(accountType)){ // 员工
            permissionType = defaultUserType;
        }
        return permissionType;
    }

    public static PropertiesPropertySource getPropertiesPropertySource(String beanName){
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = SpringContextHolder.getBean(beanName);
        PropertySources propertySources = propertySourcesPlaceholderConfigurer.getAppliedPropertySources();
        Iterator iterator = propertySources.iterator();
        while (iterator.hasNext()){
            Object obj = iterator.next();
            if(obj instanceof PropertiesPropertySource){
                PropertiesPropertySource propertiesPropertySource = (PropertiesPropertySource)obj;
                return propertiesPropertySource;
            }
        }
        return null;
    }



    /**
     * 删除数据库
     * @param dataSource
     */
    public static boolean dropDB(SysDataSource dataSource) {
        boolean result = true;
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSource.getJdbcUrl());
        druidDataSource.setUsername(dataSource.getJdbcUsername());
        druidDataSource.setPassword(dataSource.getJdbcPassword());
        druidDataSource.setDriverClassName(dataSource.getJdbcDriver());

        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName(dataSource.getJdbcDriver());

            String dbName = dataSource.getName();

            connection = DriverManager.getConnection(dataSource.getJdbcUrl(), dataSource.getJdbcUsername(), dataSource.getJdbcPassword());

            statement = connection.createStatement();

            statement.executeUpdate("DROP DATABASE IF EXISTS `" + dbName + "`");
        } catch (Exception e) {
            result = false;
        } finally {
            if(statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                }
            }

            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                }
            }
        }
        return result;
    }
}
